/**
 * 表单提交
 * */

function validateForm($formEl) {
    return new Promise((resolve, reject) => {
        const rules = {'rules': {}, 'messages': {}};
        $formEl.find(".required-validate").each(function (e) {
            $el = $(this);
            $name = $el.attr('name');
            if (!rules[$name]) {
                $type = $el.attr('type');
                rules['rules'][$name] = {};
                rules['rules'][$name]['required'] = true;
                $commonmessage = $(this).attr('placeholder');
                rules['messages'][$name] = {required: `${$commonmessage}`};
                if ($el.attr('minlength')) {
                    rules['rules'][$name]['minlength'] = $el.attr('minlength');
                    rules['messages'][$name]['minlength'] = $el.attr('minmessage') || $commonmessage;
                }
                if ($el.attr('maxlength')) {
                    rules['rules'][$name]['maxlength'] = $el.attr('maxlength');
                    rules['messages'][$name]['maxlength'] = $el.attr('maxmessage') || $commonmessage;
                }
            }
        });
        $formEl.validate({
            ...rules,
            submitHandler: function (form) {
                resolve(form);
                return false;
            }
        });
    })
}

$(".ajax-form").each(function () {
    validateForm($(this)).then(form => {
        __submitAjaxForm($(form));
    });
})

$('.ajax-post').click(function () {
    __submitAjaxForm($(this).parents('form'));
});

function __submitAjaxForm($form) {
    //加载层
    // var index = layer.load(0, {shade: [0.2, '#000']});
    var index = layer.load(0, {shade: false});
    var action = $form.attr("action");
    if (!action) {
        var url = window.location.href;
    } else {
        //取出第一个字符
        var first = action.slice(0, 1);
        if (first == '/') {
            var url = action;
        } else {
            var url = '/' + action
        }
    }

    //判断表单中是否使用了kindEditor
    var haveKindEditor = false;
    var editorName = '';
    for (var i = 0; i < $("textarea").length; i++) {
        var textareaElement = $("textarea")[i];
        if ($(textareaElement).data('editor') === 'kindEditor') {
            haveKindEditor = true;
            editorName = $(textareaElement).attr("name");
            break;
        }
    }
    if (haveKindEditor && editorName == '') {
        layer.close(index);
        layer.msg('富文本隐藏域缺少name属性');
        return;
    } else if (haveKindEditor && editorName) {
        window.editor.sync();
        //将富文本中的内容赋值到textarea隐藏域中以供表单提交
        $('textarea[name="' + editorName + '"]').val($('#' + kindEditorID).val());
    }

    var formData = $form.serialize();
    $.post(url, formData, function (res, status, xhr) {
        if (res.code === 1) {
            layer.close(index);
            toast.success(res.msg, {duration: (res.wait || 3) * 1000}).then(() => {
                window.location.href = res.url;
            });
        } else {
            layer.close(index);
            toast.error(res.msg, {duration: (res.wait || 3) * 1000}).then(() => {
                if (xhr.getResponseHeader('__token__')) {
                    $("[name='__token__']").val(xhr.getResponseHeader('__token__'));
                }
            });
        }
    }, 'json');

    setTimeout(function () {
        layer.close(index);
    }, 3000)
    return false;
}

/**
 * 初始化KindEditor富文本编辑器
 * */
var kindEditorID;

function initKindEditor(editor_id, width = 710, height = 500, items = ['source', 'undo', 'redo', '|', 'preview', 'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'clearhtml', '|', 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'link', 'unlink', '|', 'fullscreen']) {
    if (!editor_id) {
        layer.close();
        layer.msg('调用initKindEditor方法缺少富文本ID参数');
        return;
    } else {
        kindEditorID = editor_id;
    }

    KindEditor.ready(function (K) {
        window.editor = K.create('#' + editor_id, {
            width: width,
            height: height,
            items: items
        });
    });
}

/**
 * 删除
 * */
$('.ajax-del').click(function () {
    var msg = $(this).data('msg') ? $(this).data('msg') : '您确认删除吗？';
    var url = $(this).attr("href");
    swal({
        title: msg,
        type: "warning",
        cancelButtonText: '取消',
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        closeOnConfirm: false
    }, function () {
        // 加载层
        var index = layer.load(2, {content: "请稍等...", shade: [0.2, '#000']});
        $.get(url, function (res) {
            if (res.code === 1) {
                toast.success(res.msg || '删除成功', {duration: (res.wait || 3) * 1000, progressBar: true}).then(() => {
                    layer.close(index);
                    window.location.href = res.url;
                });
            } else {
                toast.error(res.msg || '删除失败', {duration: (res.wait || 3) * 1000}).then(() => {
                    layer.close(index);
                });
            }
        }, 'json');
        swal.close();
        setTimeout(function () {
            layer.close(index);
        }, 3000)
    });
    return false;
})
var ajaxModalDialog = function (e) {
    e.preventDefault();
    var url = $(this).attr("href");
    var title = $(this).data("title");
    var method = $(this).data("method");
    var timer = $(this).data("lazytime");
    swal({
        title: title || "您确认要执行该操作吗？",
        type: "warning",
        cancelButtonText: '取消',
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        closeOnConfirm: false
    }, function () {
        // 加载层
        var index = layer.load(2, {shade: [0.2, '#000']});
        $.ajax({
            url,
            type: method || "get",
            dataType: 'json',
            success: function (res) {
                if (res.code === 1) {
                    toast.success(res.msg, {duration: (res.wait || 3) * 1000}).then(() => {
                        layer.close(index);
                        window.location.href = res.url;
                    });
                } else {
                    toast.warning(res.msg, {duration: (res.wait || 3) * 1000}).then(() => {
                        layer.close(index);
                    });
                    layer.close(index);
                }
            },
            error: function (error) {
                layer.close(index);
                layer.msg(error.responseText);
            },
            complete: function () {
                setTimeout(function () {
                    layer.close(index);
                }, 3000)
            }
        });

    });
    return false;
};

$(".table-responsive")
    .on("click", ".ajax-modal-dialog", ajaxModalDialog)
/**
 * 操作
 * */
$('.ajax-operate').click(function () {
    console.log(1)
    var url = $(this).attr("href");

    swal({
        title: "您确认要执行该操作吗？",
        type: "warning",
        cancelButtonText: '取消',
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        closeOnConfirm: false
    }, function () {
        // 加载层
        var index = layer.load(2, {shade: [0.2, '#000']});

        $.get(url, function (res) {
            if (res.result === 1) {
                setTimeout(function () {
                    window.location.href = res.url;
                }, res.timer)
            } else if (res.result == 2) {
                layer.close(index);
                layer.msg(res.msg);
            }
        }, 'json');

        setTimeout(function () {
            layer.close(index);
        }, 3000)
    });
    return false;
})

/**
 * 返回上一页
 * */
$('.back-page').click(function () {
    window.history.go(-1);
})

/**
 * 清理缓存
 * */
$('#clear-cache').click(function () {
    var url = "/admin/Func/clearCache";
    $.post(url, function () {
        layer.msg('缓存清理成功')
    }, 'json')
})

/**
 * 退出登录
 * */
$('#logout').click(function () {
    var url = "/admin/Func/logout";
    $.post(url, function (res) {
        layer.msg(res.msg)
        setTimeout(function () {
            window.location.href = res.data;
        }, res.timer)
    }, 'json')
})

/**
 * 修改密码
 * */
$('#confirmUpdateAdminPwd').click(function () {
    var old_admin_pwd = $('.old_admin_pwd').val();
    var new_admin_pwd = $('.new_admin_pwd').val();
    var re_admin_pwd = $('.re_admin_pwd').val();

    if (!old_admin_pwd) {
        layer.msg('请输入原密码');
        return;
    }
    if (!new_admin_pwd) {
        layer.msg('请输入新密码');
        return;
    }
    if (!re_admin_pwd) {
        layer.msg('请输入确认密码');
        return;
    }
    if (new_admin_pwd !== re_admin_pwd) {
        layer.msg('两次密码不一致，请重新输入');
        return;
    }

    var url = "/admin/func/updateAdminPwd";

    $.post(url, {
        old_admin_pwd: old_admin_pwd,
        new_admin_pwd: new_admin_pwd
    }, function (res) {
        layer.msg(res.msg)
        if (res.result === 1) {
            $(".close-model").trigger("click");
        }
    }, 'json')
})

/**
 * @param    file_id      file上传按钮id
 * @param    btn_id       按钮id
 * */
function uploadImg(file_id, btn_id) {
    $("#" + btn_id).click(function () {
        $("#" + file_id).trigger("click");
    })

    $('#' + file_id).change(function () {
        var pic = $(this)[0].files[0];
        var formData = new FormData();
        var url = "{:U('UploadFile/uploadPicture',array('session_id'=>session_id()))}";
        formData.append('download', pic);
        $.ajax({
            url: url,
            type: "post",
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                if (data.status == 1) {
                    //上传成功
                    var id = data.id;
                    var path = data.path;
                    console.log(data);
                    return;
                    $('#img').val(id);
                    $('#uploadImg').attr('src', path);
                } else {
                    layer.msg(data.info);
                }
            }
        });
    });
}


